// pages/me/me.js

Page({

	/**
	 * 页面的初始数据
	 */

	data: {
		// signature: wx.getStorageSync('signature'),
		// token: wx.getStorageSync('token'),
		// nickName: null,
		// openId: null,

		signature: getApp().globalData.signature,
		token: getApp().globalData.token,
		nickName: getApp().globalData.nickName,
		desc: getApp().globalData.desc,
		openId: getApp().globalData.openId,
		avatarUrl: getApp().globalData.avatarUrl,
		tempAvatarUrl: null,
		tempNickName: null,
		tempDesc: null,
		show: false,
		length: 0,
		buttons: [{
			type: 'default',
			className: 'test1',
			text: '测试1',
			value: 0
		}, {
			type: 'primary',
			className: 'test2',
			text: '测试2',
			value: 1
		}],
		avaterList: [
			"/imgs/avatars/1.png",
			"/imgs/avatars/2.png",
			"/imgs/avatars/3.png",
			"/imgs/avatars/4.png",
			"/imgs/avatars/5.png",
			"/imgs/avatars/6.png",
			"/imgs/avatars/7.png",
			"/imgs/avatars/8.png",
			"/imgs/avatars/9.png",
			"/imgs/avatars/10.png",
			"/imgs/avatars/11.png",
			"/imgs/avatars/12.png",
			"/imgs/avatars/13.png",
			"/imgs/avatars/14.png",
			"/imgs/avatars/15.png",
			"/imgs/avatars/16.png",
			"/imgs/avatars/17.png",
			"/imgs/avatars/18.png",
			"/imgs/avatars/19.png",
			"/imgs/avatars/20.png",
			"/imgs/avatars/21.png",
			"/imgs/avatars/22.png",
		]
	},

	onClose() {
		this.setData({
			showDetails: false,
		})
	},

	//弹出编辑框
	popEditDesc() {
		this.setData({
			showDetails: true,
		})
	},

	//弹出编辑框
	editDesc() {
		this.setData({
			showDetails: false,
		})
		this.editWxUserBaseInfo()
	},

	//统计输入长度
	userInput: function (e) {
		// console.log("输入的内容---" + e.detail.value)
		// console.log("输入的长度---" + e.detail.value.length)
		this.setData({
			length: e.detail.value.length
		})
	},

	//选择头像
	onChooseAvatar(e) {
		console.log(e.detail.avatarUrl)
		this.setData({
			avatarUrl: e.detail.avatarUrl
		})
	},

	//选择头像
	onChooseTempAvatar(e) {
		console.log(e.detail.avatarUrl)
		this.setData({
			tempAvatarUrl: e.detail.avatarUrl
		})
	},

	//选择头像编号
	selectAvatars(e) {
		console.log(e.currentTarget.dataset.no)
		this.setData({
			avatarUrl: e.currentTarget.dataset.no,
			show: false,
		})
	},

	watchInput(e) {
		let nickName = e.detail.value
		console.log("watchInput: ", nickName)
		this.setData({
			nickName: nickName
		})
	},

	watchNameInput(e) {
		let tempNickName = e.detail.value
		console.log("watchNameInput: ", tempNickName)
		this.setData({
			tempNickName: tempNickName
		})
	},

	watchDescInput(e) {
		let tempDesc = e.detail.value
		console.log("watchDescInput: ", tempDesc)
		this.setData({
			tempDesc: tempDesc
		})
	},

	// 提交表单
	formSubmit: function (e) {
		let nickName = e.detail.value.nickName
		console.log("nickName", nickName)
		this.setData({
			nickName: nickName
		})
		wx.setStorageSync("nickName", nickName)
		this.login()
	},

	submit() {
		let nickName = this.data.nickName
		console.log("nickName", nickName)
		this.setData({
			nickName: nickName
		})
		if (this.data.avatarUrl == null || this.data.avatarUrl == "") {
			wx.showModal({
				title: '提醒',
				content: '请设置个性头像。',
				showCancel: false,
				complete: (res) => {
					if (res.confirm) {

					}
				}
			})
			return
		}
		if (nickName == null || nickName == "") {
			wx.showModal({
				title: '提醒',
				content: '请设置',
				showCancel: false,
				complete: (res) => {
					if (res.confirm) {

					}
				}
			})
			return
		}
		wx.setStorageSync("nickName", nickName)
		this.login()
	},

	// 弹出用户授权
	login() {
		wx.showLoading({
			title: '正在登录...',
		})
		// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
		console.log("头像", this.data.avatarUrl)
		console.log("昵称", this.data.nickName)
		wx.getUserInfo({
			success: (res) => {
				console.log("getUserInfo: ", res)
				if (res.signature.length != 0) {
					//保存用户WX ID
					this.setData({
						signature: res.signature
					})
					this.getOpenid()
				}
			},
			fail: (res) => {
				console.log("login failed, ", res)
			}
		}, )
	},

	//获取用户的openid
	getOpenid() {
		wx.login({
			success: (res) => {
				console.log("login:", res)
				let code = res.code
				//通过code换取openId
				wx.request({
					url: 'https://marklife.love/5h4h/user/openid?code=' + code,
					success: (res) => {
						console.log("openid: ", res.data.data.openid);
						this.setData({
							openId: res.data.data.openid
						})
						this.loginWxUser()
					}
				})
			},
		})
	},

	/**
	 * 检查登陆状态
	 * @param signature wx id 凭证
	 */
	tryToLogin() {
		console.log("tryToLogin: signature= ", this.data.signature)
		wx.request({
			url: 'https://marklife.love/mark/v1/login',
			method: 'POST',
			//传参使用form-data格式
			header: {
				'content-type': 'application/x-www-form-urlencoded' //修改此处即可
			},
			data: {
				account: this.data.signature,
				password: 'wx_password_' + this.data.signature,
			},
			success: (res) => {
				console.log("tryToLogin", res.data)
				var errCode = res.data.err
				var token = res.data.token
				if (errCode == 1000) {
					//检查登陆状态成功
					this.setData({
						token: token,
					})
					this.editWxUser()
				} else if (errCode == 1008) {
					//登陆失败，原因账户不存在
					this.tryToRegister();
				} else {
					//登陆失败 未知原因
					wx.hideLoading()
					wx.showModal({
						title: '登录失败',
						content: '抱歉，登陆失败，我也没时间去排查错误原因',
						showCancel: false,
						complete: (res) => {
							if (res.cancel) {}
							if (res.confirm) {}
						}
					})
				}
			}
		})
	},

	//编辑微信信息
	loginWxUser() {
		console.log("try to edit user")
		wx.uploadFile({
			url: 'https://marklife.love/5h4h/login',
			name: 'file',
			filePath: this.data.avatarUrl,
			header: {
				"Content-Type": "multipart/form-data",
				"token": wx.getStorageSync('token')
			},
			formData: {
				account: this.data.signature,
				password: 'wx_password_' + this.data.signature,
				wx_signature: this.data.signature,
				wx_name: this.data.nickName,
				wx_desc: '点击编辑你的个性签名',
				wx_avatar: this.data.avatarUrl,
				wx_open_id: this.data.openId,
			},
			success: (res) => {
				var data = JSON.parse(res.data)
				console.log("edit user: ", data)
				var errCode = data.err
				if (errCode == 1000 || errCode == "1000") {
					let wxInfo = data.data.wx_info
					console.log("注册成功：", wxInfo)
					this.setData({
						token: data.token,
						avatarUrl: wxInfo.wx_avatar,
						nickName: wxInfo.wx_name,
						desc: wxInfo.wx_desc,
						openId: wxInfo.wx_open_id,
						signature: wxInfo.wx_signature,
					})

					getApp().globalData.token = data.token
					getApp().globalData.avatarUrl = wxInfo.wx_avatar
					getApp().globalData.nickName = wxInfo.wx_name
					getApp().globalData.desc = wxInfo.wx_desc
					getApp().globalData.openId = wxInfo.wx_open_id
					getApp().globalData.signature = wxInfo.wx_signature
					getApp().globalData.needReRefresh = true

					wx.setStorageSync('signature', this.data.signature)
					wx.hideLoading()
					// 编辑wx信息成功提示
					wx.showToast({
						title: '登录成功',
						icon: 'success',
						duration: 2000
					})
					getApp().globalData.needReRefresh = true;
					this.checkNeedParseShareInfo()
				} else if (errCode == 1008) {
					//登陆失败，原因账户不存在
					this.tryToRegister();
				} else {
					console.log("errCode= ", errCode)
					//编辑wx信息失败 未知原因
					wx.hideLoading()
					wx.showModal({
						title: '登录失败',
						content: '抱歉，登陆失败，登录失败，我也没时间去排查错误原因',
						showCancel: false,
						complete: (res) => {
							if (res.cancel) {}
							if (res.confirm) {}
						}
					})
				}
			},
			fail: (res) => {
				console.log("edit user failed: ", res)
				wx.hideLoading()
				wx.showModal({
					title: '登录失败',
					content: '抱歉，登陆失败，编辑wx信息请求失败，我也没时间去排查错误原因',
					showCancel: false,
					complete: (res) => {
						if (res.cancel) {}
						if (res.confirm) {}
					}
				})
			}
		})
	},

	//编辑微信信息
	editWxUser() {
		console.log("try to edit user")
		wx.uploadFile({
			url: 'https://marklife.love/5h4h/user/edit',
			name: 'file',
			filePath: this.data.avatarUrl,
			header: {
				"Content-Type": "multipart/form-data",
				"token": wx.getStorageSync('token')
			},
			formData: {
				token: this.data.token,
				wx_signature: this.data.signature,
				wx_name: this.data.nickName,
				wx_desc: '点击编辑你的个性签名',
				wx_avatar: this.data.avatarUrl,
				wx_open_id: this.data.openId,
			},
			success: (res) => {
				var data = JSON.parse(res.data)
				console.log("edit user: ", data)
				var errCode = data.err
				if (errCode == 1000 || errCode == "1000") {
					let wxInfo = data.data.wx_info
					console.log("编辑wx信息成功：", wxInfo)
					this.setData({
						token: data.token,
						avatarUrl: wxInfo.wx_avatar,
						nickName: wxInfo.wx_name,
						desc: wxInfo.wx_desc,
						openId: wxInfo.wx_open_id,
						signature: wxInfo.wx_signature,
					})

					getApp().globalData.token = data.token
					getApp().globalData.avatarUrl = wxInfo.wx_avatar
					getApp().globalData.nickName = wxInfo.wx_name
					getApp().globalData.desc = wxInfo.wx_desc
					getApp().globalData.openId = wxInfo.wx_open_id
					getApp().globalData.signature = wxInfo.wx_signature
					getApp().globalData.needReRefresh = true

					wx.setStorageSync('signature', this.data.signature)
					wx.hideLoading()
					// 编辑wx信息成功提示
					wx.showToast({
						title: '登录成功',
						icon: 'success',
						duration: 2000
					})
					getApp().globalData.needReRefresh = true;
					this.checkNeedParseShareInfo()
				} else {
					console.log("errCode= ", errCode)
					//编辑wx信息失败 未知原因
					wx.hideLoading()
					wx.showModal({
						title: '登录失败',
						content: '抱歉，登陆失败，编辑wx信息失败，我也没时间去排查错误原因',
						showCancel: false,
						complete: (res) => {
							if (res.cancel) {}
							if (res.confirm) {}
						}
					})
				}
			},
			fail: (res) => {
				console.log("edit user failed: ", res)
				wx.hideLoading()
				wx.showModal({
					title: '登录失败',
					content: '抱歉，登陆失败，编辑wx信息请求失败，我也没时间去排查错误原因',
					showCancel: false,
					complete: (res) => {
						if (res.cancel) {}
						if (res.confirm) {}
					}
				})
			}
		})
	},

	//编辑微信信息
	editWxUserBaseInfo() {
		console.log("tempAvatar=", this.data.tempAvatarUrl)
		console.log("tempName=", this.data.tempNickName)
		console.log("tempDesc=", this.data.tempDesc)
		if (this.data.tempNickName == null || this.data.tempNickName == "") {
			this.setData({
				tempNickName: this.data.nickName,
			})
		}
		if (this.data.tempDesc == null || this.data.tempDesc == "") {
			this.setData({
				tempDesc: this.data.desc,
			})
		}
		if (this.data.tempAvatarUrl == null || this.data.tempAvatarUrl == "") {
			wx.showLoading({
				title: '',
			})
			this.editNameAndDesc()
			return
		}
		wx.showLoading({
			title: '',
		})
		console.log("try to edit user desc token= " + this.data.token)
		console.log("try to edit user desc desc= " + this.data.tempDesc)
		this.editNameDescAndAvatar()
	},

	//编辑名称和签名
	editNameAndDesc(){
		wx.request({
			url: "https://marklife.love/5h4h/user/edit/info2",
			method: 'POST',
			//传参使用form-data格式
			header: {
				'content-type': 'application/x-www-form-urlencoded' //修改此处即可
			},
			data: {
				token: this.data.token,
				wx_name: this.data.tempNickName,
				wx_desc: this.data.tempDesc,
			},
			complete: (res) => {
				wx.hideLoading()
			},
			success: (res) => {
				console.log("edit user base info: ", res.data)
				var errCode = res.data.err
				console.log("errCode = " + errCode)
				if (errCode == 1000 || errCode == "1000") {
					let wxInfo = res.data.data.wx_info
					console.log("编辑wx信息成功：", wxInfo)
					this.setData({
						avatarUrl: wxInfo.wx_avatar,
						nickName: wxInfo.wx_name,
						desc: wxInfo.wx_desc,
					})

					getApp().globalData.avatarUrl = wxInfo.wx_avatar
					getApp().globalData.nickName = wxInfo.wx_name
					getApp().globalData.desc = wxInfo.wx_desc
					getApp().globalData.needReRefresh = true

					// 编辑wx信息成功提示
					wx.showToast({
						title: '修改个人信息成功',
						icon: 'success',
						duration: 2000
					})
					getApp().globalData.needReRefresh = true;
					this.checkNeedParseShareInfo()
				} else {
					console.log("errCode= ", errCode)
					//编辑wx信息失败 未知原因
					wx.showModal({
						title: '修改个人信息失败',
						content: '抱歉，修改个人信息失败，编辑wx信息失败，我也没时间去排查错误原因',
						showCancel: false,
						complete: (res) => {
							if (res.cancel) {}
							if (res.confirm) {}
						}
					})
				}
			},
			fail: (res) => {
				console.log("edit user failed: ", res)
				wx.hideLoading()
				wx.showModal({
					title: '登录失败',
					content: '抱歉，登陆失败，编辑wx信息请求失败，我也没时间去排查错误原因',
					showCancel: false,
					complete: (res) => {
						if (res.cancel) {}
						if (res.confirm) {}
					}
				})
			}
		})
	},

	//编辑名称签名还有头像
	editNameDescAndAvatar(){
		wx.uploadFile({
			url: 'https://marklife.love/5h4h/user/edit/info',
			name: 'file',
			filePath: this.data.tempAvatarUrl,
			header: {
				"Content-Type": "multipart/form-data",
				"token": wx.getStorageSync('token')
			},
			formData: {
				token: this.data.token,
				wx_name: this.data.tempNickName,
				wx_desc: this.data.tempDesc,
			},
			complete: (res) => {
				wx.hideLoading()
			},
			success: (res) => {
				console.log("edit user base info: ", res.data)
				var data = JSON.parse(res.data)
				var errCode = data.err
				console.log("errCode = " + errCode)
				if (errCode == 1000 || errCode == "1000") {
					let wxInfo = data.data.wx_info
					console.log("编辑wx信息成功：", wxInfo)
					this.setData({
						avatarUrl: wxInfo.wx_avatar,
						nickName: wxInfo.wx_name,
						desc: wxInfo.wx_desc,
					})

					getApp().globalData.avatarUrl = wxInfo.wx_avatar
					getApp().globalData.nickName = wxInfo.wx_name
					getApp().globalData.desc = wxInfo.wx_desc
					getApp().globalData.needReRefresh = true

					// 编辑wx信息成功提示
					wx.showToast({
						title: '修改个人信息成功',
						icon: 'success',
						duration: 2000
					})
					getApp().globalData.needReRefresh = true;
					this.checkNeedParseShareInfo()
				} else {
					console.log("errCode= ", errCode)
					//编辑wx信息失败 未知原因
					wx.showModal({
						title: '修改个人信息失败',
						content: '抱歉，修改个人信息失败，编辑wx信息失败，我也没时间去排查错误原因',
						showCancel: false,
						complete: (res) => {
							if (res.cancel) {}
							if (res.confirm) {}
						}
					})
				}
			},
			fail: (res) => {
				console.log("edit user failed: ", res)
				wx.hideLoading()
				wx.showModal({
					title: '登录失败',
					content: '抱歉，登陆失败，编辑wx信息请求失败，我也没时间去排查错误原因',
					showCancel: false,
					complete: (res) => {
						if (res.cancel) {}
						if (res.confirm) {}
					}
				})
			}
		})
	},

	checkNeedParseShareInfo() {
		if (getApp().globalData.shareKey != null && getApp().globalData.shareKey.length > 0) {
			wx.switchTab({
				url: '/pages/todo/todo',
			})
		}
	},

	//尝试注册
	tryToRegister() {
		wx.request({
			url: 'https://marklife.love/mark/v1/register',
			method: 'POST',
			//传参使用form-data格式
			header: {
				'content-type': 'application/x-www-form-urlencoded' //修改此处即可
			},
			data: {
				account: this.data.signature,
				password: 'wx_password_' + this.data.signature,
			},
			success: (res) => {
				var errCode = res.data.err
				if (errCode == 1000) {
					console.log("注册成功")
					this.loginWxUser()
				} else {
					//登陆失败 未知原因
					wx.hideLoading()
					wx.showModal({
						title: '登录失败',
						content: '抱歉，注册失败，我也没时间去排查错误原因',
						showCancel: false,
						complete: (res) => {
							if (res.cancel) {}
							if (res.confirm) {}
						}
					})
				}
			},
			fail: (res) => {
				wx.hideLoading()
				wx.showModal({
					title: '登录失败',
					content: '抱歉，注册请求失败，我也没时间去排查错误原因',
					showCancel: false,
					complete: (res) => {
						if (res.cancel) {}
						if (res.confirm) {}
					}
				})
			}
		})
	},

	//注销授权
	logout(e) {
		var that = this
		wx.showModal({
			title: '温馨提示',
			content: '确定要退出登录吗？',
			success(res) {
				if (res.confirm) {
					// 清空缓存
					wx.setStorageSync('signature', null)
					that.setData({
						signature: null,
						token: null,
						avatarUrl: null,
						nickName: null
					})
					getApp().globalData.token = null
					getApp().globalData.avatarUrl = null
					getApp().globalData.nickName = null
					getApp().globalData.desc = null
					getApp().globalData.signature = null
					wx.showToast({
						title: '退出成功',
						icon: 'success',
						duration: 2000,
					})
				}
			}
		})
	},

	toggleAvatarsDialog: function () {
		this.setData({
			show: true
		})
	},


	/**
	 * 检查登陆状态
	 * @param signature wx id 凭证
	 */
	checkLogin() {
		console.log("checkLogin: signature= ", this.data.signature)
		wx.request({
			url: 'https://marklife.love/mark/v1/login',
			method: 'POST',
			//传参使用form-data格式
			header: {
				'content-type': 'application/x-www-form-urlencoded' //修改此处即可
			},
			data: {
				account: this.data.signature,
				password: 'wx_password_' + this.data.signature,
			},
			success: (res) => {
				console.log("checkLogin", res.data)
				var errCode = res.data.err
				var token = res.data.token
				if (errCode == 1000) {
					wx.hideLoading()
					//登陆成功
					//保存用户的登陆token
					let wxInfo = res.data.data.wx_info
					this.setData({
						token: token,
						avatarUrl: wxInfo.wx_avatar,
						nickName: wxInfo.wx_name,
						desc: wxInfo.wx_desc,
						openId: wxInfo.wx_open_id,
						signature: wxInfo.wx_signature,
					})
					getApp().globalData.token = token
					getApp().globalData.avatarUrl = wxInfo.wx_avatar
					getApp().globalData.nickName = wxInfo.wx_name
					getApp().globalData.desc = wxInfo.wx_desc
					getApp().globalData.openId = wxInfo.wx_open_id
					getApp().globalData.signature = wxInfo.wx_signature
				}
			}
		})
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		this.setData({
			signature: getApp().globalData.signature,
			token: getApp().globalData.token,
			nickName: getApp().globalData.nickName,
			desc: getApp().globalData.desc,
			openId: getApp().globalData.openId,
			avatarUrl: getApp().globalData.avatarUrl,
		})

		console.log("token: ", this.data.token)
		if (this.data.signature == null) {

			return;
		}

		if (this.data.token == null) {
			this.checkLogin()
		}

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})